<template>
  <div id="div">
    <h2>人员列表</h2>
    <input type="text" placeholder="请输入名字" v-model="obj.keyWord" />
    <button @click="obj.sortType = 2">年龄升序</button>
    <button @click="obj.sortType = 1">年龄降序</button>
    <button @click="obj.sortType = 0">原顺序</button>
    <ul>
      <li v-for="(p, index) of filPerson" :key="index">
        {{ p.name }}--{{ p.age }}--{{ p.sex }}
      </li>
    </ul>
  </div>
</template>

<script setup>
  import { ref, reactive, watch, computed,onmounted } from "vue";
onMounted(() => {
 let ul= document.querySelector('ul')
 console.log(ul);
});
  const obj = reactive({
    sortType: "", //0原顺序  1降序  2升序
    person: [
      { id: 1, name: "马冬梅", age: 48, sex: '女' },
      { id: 2, name: "周冬雨", age: 20, sex: '女' },
      { id: 3, name: "周杰伦", age: 38, sex: '男' },
      { id: 4, name: "周星驰", age: 53, sex: '男' },
    ],
    keyWord: "",
    // filPerson: [], //要在新的数组上进行赋值，不要改变原数组
  });
  let filPerson = computed(() => {
    const arr = obj.person.filter((p) => {
      return p.name.indexOf(obj.keyWord) !== -1;
    });
    //排序
    if (obj.sortType) {
      arr.sort((p1, p2) => {
        return obj.sortType === 1 ? p2.age - p1.age : p1.age - p2.age;
      });
    }
    return arr;
  });

  // watch(() => obj.keyWord,
  //   (val) => {
  //     obj.filPerson = obj.person.filter((p) => {
  //       return p.name.indexOf(val) !== -1
  //     })
  //   },
  //   { immediate: true })  //页面一渲染就执行一次
</script>

<style scoped>
  #div {
    margin-top: 10vh;
  }
</style>